import React, {
    createContext,
    useContext,
    useState,
} from "react";
import {
    getCalculate, getCalculateChildren, getCalculateOverview, getTimeSlot,
} from "../services/index";
import {ICalculate, ITimeSlot} from "../types/calculate";
import {showToast} from "../utils/toast";

interface CalculateContextData {
    calculatesMaxTime: number;
    calculates: ICalculate[];
    timeSlot: ITimeSlot[];
    setCalculates: () => Promise<void>;
    loadCalculate: () => Promise<void>;
    loadCalculateOverview: () => Promise<void>;
    loadCalculateChildren: () => Promise<void>;
    loadTimeSlot: () => Promise<void>;
}

const CalculateContext = createContext({} as CalculateContextData);

interface CalculateProviderProps {
    children: React.ReactNode;
}

export const CalculateProvider: React.FC<CalculateProviderProps> = ({ children }) => {

    const [calculates, setCalculates] = useState([]);
    const [calculatesMaxTime, setCalculatesMaxTime] = useState(100);
    const [timeSlot, setTimeSlot] = useState([]);

    async function loadCalculate(params) {
        const res = await getCalculate(params);
        console.log('--loadCalculate-res-',res)
        if (res.code == 0) {
            setCalculates(res.data?.events||[]);
            setCalculatesMaxTime(res.data?.maxTime || 100);
        } else {
            showToast("error", "出错了", res?.msg);
        }
    }

    async function loadTimeSlot(params) {
        const res = await getTimeSlot(params);
        console.log('--loadTimeSlot-res-',res)
        if (res.code == 0) {
            setTimeSlot(res.data?.dates||[]);
        } else {
            showToast("error", "出错了", res?.msg);
        }
    }

    async function loadCalculateChildren(params) {
        const res = await getCalculateChildren(params);
        console.log('--loadCalculateChildren-res-',res)
        if (res.code == 0) {
            setCalculatesMaxTime(res.data?.maxTime || 100);
            setCalculates(res.data?.events||[]);
        } else {
            showToast("error", "出错了", res?.msg);
        }
    }

    async function loadCalculateOverview(params) {
        const res = await getCalculateOverview(params);
        console.log('--getCalculateOverview-res-',res)
        return res;
    }

    return (
        <CalculateContext.Provider
            value={{
                timeSlot,
                calculates,
                calculatesMaxTime,
                setCalculates,
                loadCalculate,
                loadTimeSlot,
                loadCalculateChildren,
                loadCalculateOverview,
            }}
        >
            {children}
        </CalculateContext.Provider>
    );
};

export function useCalculate() {
    const context = useContext(CalculateContext);

    if (!context) throw new Error("useCalculate must be used inside a CalculateProvider");

    return context;
}
